package com.artisan.medium.app.utils;

import com.artisan.medium.app.jwt.JWTSigner;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.JWTVerifyException;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
import java.util.HashMap;
import java.util.Map;

public class TokenUtils {
    final static String net = "";
    final static String secret = "{{secret used for signing}}";
    final static JWTSigner signer = new JWTSigner(secret);
    final static JWTVerifier jwtVerifier=new JWTVerifier(secret);
    final static HashMap<String, Object> claims = new HashMap<String, Object>();

    public static String getToken(String uid,String data,String Cipher,String did){
        claims.put("uid", uid);
        claims.put("net", net);
        claims.put("data", data);
        claims.put("Cipher", Cipher);
        claims.put("did", did);
        final String s_key = signer.sign(claims);
        return s_key;
    }


    public static Map<String,Object> getTokenMap(String token){
        Map<String,Object>jwtMap=null;
        try {
            jwtMap= jwtVerifier.verify(token);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SignatureException e) {
            e.printStackTrace();
        } catch (JWTVerifyException e) {
            e.printStackTrace();
        }catch (Exception e){
            e.printStackTrace();
        }
        return jwtMap;
    }

    public static long getTokenUid(String token){
        Map<String,Object>jwtMap=null;
        long uid=-1;
        try {
            jwtMap= jwtVerifier.verify(token);
            uid=Long.valueOf(String.valueOf(jwtMap.get("uid")));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SignatureException e) {
            e.printStackTrace();
        } catch (JWTVerifyException e) {
            e.printStackTrace();
        }catch (Exception e){
            e.printStackTrace();
        }
        return uid;
    }
}
